<?php

declare(strict_types=1);

namespace App\Admin;

use App\Entity\AdminUser;
use App\Entity\Page;
use App\Entity\PageTag;
use App\Utils\Helper\GeneralHelper;
use App\Utils\Helper\GetterHelper;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Security;

final class PageTagAdmin extends AbstractAdmin {

    protected $baseRouteName = 'admin_page_tag';
    protected $baseRoutePattern = 'page_tag';
    protected $maxPageLinks = 10;
    protected $security;

    public function __construct ($code, $class, $baseControllerName, Security $security) {
        parent::__construct($code, $class, $baseControllerName);
        $this->security = $security;
    }

    protected function configureDefaultSortValues (array &$sortValues) {
        $sortValues['_page'] = 1;
        $sortValues['_per_page'] = 32;
        $sortValues['_sort_order'] = 'DESC';
        $sortValues['_sort_by'] = 'id';
    }

    public function toString ($object) {
        return $object instanceof PageTag ? $object->getValue() : '标签';
    }

    protected function configureDatagridFilters (DatagridMapper $datagridMapper): void {
        $datagridMapper
            ->add('value', null, ['label' => '标签'])
            ->add('admin_user_id', 'doctrine_orm_choice', [
                'label' => '创建人',
            ], ChoiceType::class, [
                'choices' => array_flip(GetterHelper::getEntityManager()->getRepository(AdminUser::class)->findAllToArray()),
            ]);
    }

    protected function configureListFields (ListMapper $listMapper): void {
        $listMapper
            ->addIdentifier('value', null, [
                'label'        => '标签',
                'header_style' => 'width: 60%; text-align: left',
                'row_align'    => 'left',
            ])
            ->add('admin_user_id', null, [
                'label'        => '创建人',
                'header_style' => 'width: 15%; text-align: center',
                'row_align'    => 'center',
                'admin_users'  => GetterHelper::getEntityManager()->getRepository(AdminUser::class)->findAllToArray(),
                'template'     => 'backend/public/list_admin_user_id.html.twig',
            ])
            ->add('created_at', null, [
                'format'       => 'Y-m-d H:i:s',
                'timezone'     => 'PRC',
                'label'        => '创建时间',
                'header_style' => 'width: 15%; text-align: center',
                'row_align'    => 'center',
            ]);
    }

    protected function configureFormFields (FormMapper $formMapper): void {
        $formMapper
            ->add('value', null, ['label' => '标签']);
    }

    protected function configureShowFields (ShowMapper $showMapper): void {
        $showMapper
            ->add('id')
            ->add('value')
            ->add('created_at')
            ->add('updated_at');
    }

    protected function configureRoutes (RouteCollection $collection) {
        parent::configureRoutes($collection); // TODO: Change the autogenerated stub
        $collection->remove('export');
        $collection->remove('show');
    }

    public function prePersist ($object) {
        parent::prePersist($object); // TODO: Change the autogenerated stub

        $object->setAdminUserId($this->security->getUser()->getId());
        $object->setCreatedAt(new \DateTime());
    }

    public function preRemove ($object) {
        $page_count = GetterHelper::getEntityManager()->getRepository(Page::class)->getPageCountByPageTagId($object->getId());
        if ($page_count) {
            GeneralHelper::getOneInstance()->addFlash('sonata_flash_error', '该标签有文章关联不能删除');
            $url = $this->generateUrl('list', $this->getFilterParameters());
            header("Location:".$url);
            exit();
        }
    }

    public function preBatchAction ($actionName, ProxyQueryInterface $query, array &$idx, $allElements) {
        switch ($actionName) {
            case 'delete':
                // 删除时校验
                if ($allElements == 'on') {
                    $idx = GetterHelper::getEntityManager()->getRepository(PageTag::class)->getIds();
                }
                foreach ($idx as $id) {
                    $page_count = GetterHelper::getEntityManager()->getRepository(Page::class)->getPageCountByPageTagId($id);
                    if ($page_count) {
                        GeneralHelper::getOneInstance()->addFlash('sonata_flash_error', '所选择的数据有文章关联，不能被执行批量删除操作');
                        $url = $this->generateUrl('list', $this->getFilterParameters());
                        header("Location:".$url);
                        exit();
                    }
                }
                break;
            default:
                parent::preBatchAction($actionName, $query, $idx, $allElements);
        }
    }
}
